package leetcode;

/**
 * @author yinlei
 * @date 2018/6/20
 * @since 1.0.0
 */
public class N008StringToInteger_atoi {

    public static void main(String[] args) {
//        System.out.println('c' + 1);
        System.out.println('+'+0);
        System.out.println('-'+0);
        System.out.println((char) 44);
        System.out.println(myAtoi("123"));
        System.out.println(myAtoi("  1123"));
        System.out.println(myAtoi("  -123"));
        System.out.println(myAtoi("-123"));
        System.out.println(myAtoi("a123"));
        System.out.println(myAtoi("  -a123"));
        System.out.println(myAtoi("123b"));
        System.out.println(myAtoi("-91283472332"));
        System.out.println(myAtoi("words and 987"));
        System.out.println(myAtoi("4193 with words"));
        System.out.println(myAtoi("+0"));
        System.out.println(myAtoi("+123"));
        System.out.println(myAtoi("+-123"));
        System.out.println(myAtoi("-+123"));
        System.out.println(myAtoi("   +01 123"));
        System.out.println(myAtoi("   +2-1"));
        System.out.println(myAtoi("   0-1"));
        System.out.println(myAtoi("   -1+2"));
    }

    static public int myAtoi(String str) {
        char[] chars = str.trim().toCharArray();
        int result = 0;
        int factor = 1;
        int intOffset = '0';

        int d = Integer.MAX_VALUE / 10;

        for (int i = 0, n = chars.length; i < n; i++) {
            char c = chars[i];
            if (i == 0 && (c == '-' || c == '+')) {
                if (i + 1 < n && notDigit(chars[i + 1]))
                    break;
                factor = 44 - c;
                continue;
            } else if (notDigit(c)) {
                break;
            }

            // 溢出判断
            int data = c - intOffset;
            if (result > d || (result == d && data > 7)) {
                return factor == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }

            result = result * 10 + data;
        }

        return result * factor;
    }

    private static boolean notDigit(char c) {
        return c < '0' || c > '9';
    }

}
